package com.gateway.api.util;

import javax.servlet.http.HttpServletRequest;
import java.security.NoSuchAlgorithmException;

/**
 * @Description:
 * @author: shaoyu1
 * @date: 2019/11/15 13:57
 */
public class LoginUtil {

    public static boolean checkUser(HttpServletRequest req,String username,String password){
        String sessionId = req.getSession().getId();
        String user_agent = req.getHeader("user-agent");
        if(checkUserAndPassword(username,password)){
            try {
                String cacheKey = MD5Util.encode(sessionId+"|"+user_agent+"|username");
                CacheUtil cacheUtil = BeanUtil.getBean(CacheUtil.class);
                cacheUtil.set(cacheKey,username,20*60);
                return true;
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }

    private static boolean checkUserAndPassword(String username, String password) {
        return true;
    }

    public static boolean checkLogin(HttpServletRequest req){
        String sessionId = req.getSession().getId();
        String user_agent = req.getHeader("user-agent");
        try {
            String cacheKey = MD5Util.encode(sessionId+"|"+user_agent+"|username");
            CacheUtil cacheUtil = BeanUtil.getBean(CacheUtil.class);
            Object username = cacheUtil.get(cacheKey);
            if(username!=null){
                cacheUtil.set(cacheKey,username,20*60);
                return true;
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    public static String getUsername(HttpServletRequest req){
        String sessionId = req.getSession().getId();
        String user_agent = req.getHeader("user-agent");
        try {
            String cacheKey = MD5Util.encode(sessionId+"|"+user_agent+"|username");
            CacheUtil cacheUtil = BeanUtil.getBean(CacheUtil.class);
            Object username = cacheUtil.get(cacheKey);
            if(username!=null){
                return username.toString();
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
        return "";
    }

    public static void logout(HttpServletRequest req) {
        try {
            String sessionId = req.getSession().getId();
            String user_agent = req.getHeader("user-agent");
            String cacheKey = MD5Util.encode(sessionId+"|"+user_agent+"|username");
            CacheUtil cacheUtil = BeanUtil.getBean(CacheUtil.class);
            cacheUtil.del(cacheKey);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
}
